package com.atguigu.flink.window;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * Created by Smexy on 2023/11/14
        Aggregate对比reduce特点是输入和输出的类型可以不一样
 */
public class Demo7_Aggregate
{
    public static void main(String[] args) {

        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 3333);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);

                env
                   .socketTextStream("hadoop102", 8888)
                   .map(new WaterSensorMapFunction())
                    .countWindowAll(5l)
                   /*
                    AggregateFunction<IN, ACC, OUT>
                        IN: 输入
                        ACC: 累加器，自己定义
                        OUT： 输出，自定义
                    */
                    .aggregate(new AggregateFunction<WaterSensor, Integer, String>()
                    {
                        //创建一个累加器对象,Task被创建时，只调用一次
                        @Override
                        public Integer createAccumulator() {
                            return 0;
                        }

                        //把输入的数据进行聚合。每来一条元素，调用一次
                        @Override
                        public Integer add(WaterSensor value, Integer accumulator) {
                            System.out.println("Demo7_Aggregate.add");
                            return accumulator + value.getVc();
                        }

                        //从ACC中获取最终的结果。窗口触发计算时，调用一次
                        @Override
                        public String getResult(Integer accumulator) {
                            return "sumVC:" + accumulator;
                        }

                        //无需实现，批处理才需要
                        @Override
                        public Integer merge(Integer a, Integer b) {
                            return null;
                        }
                    })
                    .print();


                try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

    }
}
